﻿using System;
using System.Collections.Generic;
using System.Linq;
using context;
using entities;

namespace DataAccessLibrary.DAL
{
    public class SupplyDAO
    {
        public List<SupplyDetail> SelectSupplyDetails(int available)
        {
            using (var ctx = new BlueMDataContext())
            {
                IQueryable<SupplyDetail> query = ctx.SupplyDetails;

                if (available > -1)
                {
                    query = query.Where(p => p.Available == Convert.ToBoolean(available));
                }
                return query.ToList();
            }
        }

        public SupplyDetail SelectSupplyDetail(int supplyDetailId)
        {
            using (var ctx = new BlueMDataContext())
            {
                return ctx.SupplyDetails.First(p => p.SupplyDetailID == supplyDetailId);
            }
        }

        public List<SupplyDetail> SelectSupplyDetails(string supplyDetailName, int available)
        {
            using (var ctx = new BlueMDataContext())
            {
                IQueryable<SupplyDetail> query = ctx.SupplyDetails.Where(p => p.SupplyName.Contains(supplyDetailName));
                if (available > -1)
                {
                    query = query.Where(p => p.Available);
                }
                return query.ToList();
            }
        }

        public bool InsertSupplyDetail(SupplyDetail supplyDetail)
        {
            using (var ctx = new BlueMDataContext())
            {
                ctx.SupplyDetails.InsertOnSubmit(supplyDetail);
                ctx.SubmitChanges();
            }

            return true;
        }

        public bool UpdateSupplyDetail(SupplyDetail supplyDetail)
        {
            using (var ctx = new BlueMDataContext())
            {
                SupplyDetail updateSupplyDetail =
                    ctx.SupplyDetails.First(p => p.SupplyDetailID == supplyDetail.SupplyDetailID);
                updateSupplyDetail.SupplyName = supplyDetail.SupplyName;
                updateSupplyDetail.SupplyPrice = supplyDetail.SupplyPrice;
                updateSupplyDetail.Available = supplyDetail.Available;
                updateSupplyDetail.Unit = supplyDetail.Unit;
                ctx.SubmitChanges();
            }

            return true;
        }

        public bool InsertSupplies(IEnumerable<Supply> supplies)
        {
            using (var ctx = new BlueMDataContext())
            {
                ctx.Supplies.InsertAllOnSubmit(supplies);
                ctx.SubmitChanges();
            }
            return true;
        }

        public List<Supply> SelectSupplies(int checkinId)
        {
            using (var ctx = new BlueMDataContext())
            {
                return ctx.Supplies.Where(p => p.CheckInID == checkinId).ToList();
            }
        }
    }
}